from docx import Document
from pathlib import Path
import requests
import time
import json
import os
import io

# async def get_word_page_limit(word_path):
#     s_time = time.time()
#     document = Document(word_path)
#     full_text = ''
#     limit = True
#     for index, paragraph in enumerate(document.paragraphs):
#         if not paragraph.text.strip():
#             continue
#         else:
#             full_text += paragraph.text
#             if len(full_text) > 6000:
#                 limit = False
#                 break
#     e_time = time.time()
#     print('判断word是否超出限制 总耗时', e_time - s_time)
#
#     return limit

async def get_word_page_limit(fileId: str, DownloadDataName: str, l_sign: str, Authorization: str):
    s_time = time.time()
    # 如果句子docx已经存在 则直接返回文件流

    # 接口 URL
    url = 'http://192.168.2.152:8253/IBAgent/exportFile'

    headers = {
        'Authorization': Authorization,
        'Content-Type': 'application/json'  # 根据实际情况可能需要调整
    }

    data = {
        "fileId": fileId,
        "_DownloadDataName": DownloadDataName,
        "l_sign": l_sign
    }

    # 将数据转换为 JSON 格式
    json_data = json.dumps(data)

    # 发送 POST 请求
    response = requests.post(url, headers=headers, data=json_data)
    # 检查响应状态码
    if response.status_code == 200:
        # 获取响应的字节流
        bytes_stream = response.content
        print(type(bytes_stream))
        # print(bytes_stream)

        # 将字节流转换为 BytesIO 对象
        bytes_io = io.BytesIO(bytes_stream)

    else:
        print(f"C0 error: {response.status_code}")

        raise ValueError(
            f"C0 error: {response.status_code}, response: {response.text}")

    # 使用 python-docx 库读取 Word 文档
    document = Document(bytes_io)

    full_text = ''
    limit = True
    for index, paragraph in enumerate(document.paragraphs):
        if not paragraph.text.strip():
            continue
        else:
            full_text += paragraph.text
            if len(full_text) > 6000:
                limit = False
                break
    e_time = time.time()
    print('判断word是否超出限制 总耗时', e_time - s_time)

    return limit

if __name__ == '__main__':
    import asyncio
    page_limit = asyncio.run(get_word_page_limit('../sentence_docx/测试.docx'))
    print(page_limit)